Valid anagram¶
Time: O(N); Space: O(1); easy
Given two strings s and t, write a function to determine if t is an anagram of s.
Example 1:
Input: s = “anagram”, t = “nagaram”
Output: True
Example 2:
Input: s = “rat”, t = “car”
Output: False
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
[ ]:
class Solution1(object):
def isAnagram(self, s, t):
"""
:type s: string
:type t: string
:rtype: boolean
"""
if len(s) != len(t):
return False
count = {}
for c in s:
if c.lower() in count:
count[c.lower()] += 1
else:
count[c.lower()] = 1
for c in t:
if c.lower() in count:
count[c.lower()] -= 1
else:
count[c.lower()] = -1
if count[c.lower()] < 0:
return False
return True
[ ]:
sol = Solution1()
s = "anagram"
t = "nagaram"
assert sol.isAnagram(s, t) == True
s = "rat"
t = "car"
assert sol.isAnagram(s, t) == False
[ ]:
class Solution2(object):
def isAnagram2(self, s, t):
return all([s.count(c)==t.count(c) for c in string.ascii_lowercase])
[ ]:
sol = Solution2()
s = "anagram"
t = "nagaram"
assert sol.isAnagram(s, t) == True
s = "rat"
t = "car"
assert sol.isAnagram(s, t) == False
[ ]:
class Solution3(object):
def isAnagram3(self, s, t):
if len(s) != len(t):
return False
count = collections.defaultdict(int)
for c in s:
count[c] += 1
for c in t:
count[c] -= 1
if count[c] < 0:
return False
return True
[ ]:
sol = Solution3()
s = "anagram"
t = "nagaram"
assert sol.isAnagram(s, t) == True
s = "rat"
t = "car"
assert sol.isAnagram(s, t) == False
[ ]:
class Solution4(object):
"""
Time: O(NLogN)
Space: O(N)
"""
def isAnagram(self, s, t):
:type s: string
:type t: string
:rtype: bool
return sorted(s) == sorted(t)
[2]:
sol = Solution4()
s = "anagram"
t = "nagaram"
assert sol.isAnagram(s, t) == True
s = "rat"
t = "car"
assert sol.isAnagram(s, t) == False
Related problems:¶
https://www.lintcode.com/problem/compare-strings
https://www.lintcode.com/problem/anagrams
https://www.lintcode.com/problem/string-permutation
https://www.lintcode.com/problem/substring-rotation
https://www.lintcode.com/problem/anagram-map-reduce
https://www.lintcode.com/problem/find-all-anagrams-in-a-string